<template>
  <div>
    <el-form ref="form" :model="form" label-width="auto" >
      <el-form-item label="朗读标题">
        <el-input v-model="form.topic" style="width: 300px"></el-input>
      </el-form-item>
      <el-form-item label="朗读权限">
        <el-switch
          v-model="form.isPublic"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-value="1"
          inactive-value="0"
        >
        </el-switch>
      </el-form-item>
      <el-form-item label="标签">
        <el-input v-model="tagName" style="width: 150px"></el-input>
        <el-button size="mini" type="success" icon="el-icon-check" @click="addTag" circle></el-button>
        <el-tag
          v-for="tag in form.tagNames"
          :key="tag.name"
          @close="closeTag(tag)"
          closable
          :type="tag.type">
          {{tag.name}}
        </el-tag>
      </el-form-item>
      <el-form-item label="朗读封面">
        <el-col :span="4">
          <el-upload
            class="avatar-uploader"
            action="http://47.110.93.58:8081/user/myDesign/add/myReadImage"
            :show-file-list="true"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="form.picture" :src="form.picture" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-col>
      </el-form-item>
      <el-form-item label="朗读故事">
        <el-input type="textarea" v-model="form.content" style="width: 300px"></el-input>
      </el-form-item>
      <el-form-item label="朗读音频">
        <el-col :span="4">
          <el-select v-model="form.region"
                   placeholder="请选择音频来源" >
          <el-option label="本地" value="local"></el-option>
          <el-option label="在线录音" value="online"></el-option>
        </el-select>
        </el-col>
        <el-col :span="20" v-if="form.region == 'online'">
            <el-button @click="recordStart" type="primary">录音</el-button>
            <el-button @click="resume">继续</el-button>
            <el-button @click="pause" type="info">暂停</el-button>
            <el-button @click="stop" type="warning">停止</el-button>
            <Button type="info" @click="getMp3Data()" style="margin:1vw;">下载音频</Button>
            <el-button @click="upVideo">上传音频</el-button>
          <i v-if="this.number != undefined" style="color: #2b2f3a">时长:{{this.number}} </i>
        </el-col>
        <el-col :span="20" v-if="form.region == 'local'">
          <el-upload
            class="upload-demo"
            action="http://47.110.93.58:8081/user/myDesign/add/myReadVideo"
            :before-upload="beforeAvatarUploadVideo"
            multiple
            :limit="1"
            :on-exceed="handleExceed"
            :on-success="uploadSuccess"
            :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-col>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即发布</el-button>
        <el-button @click="back">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import Recorder from 'js-audio-recorder';
import {addMyRead} from "@/api/myDesign";
import axios from 'axios'
const lamejs = require('lamejs')
const recorder = new Recorder({
  //sampleBits: 16,                 // 采样位数，支持 8 或 16，默认是16
  //sampleRate: 48000,              // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000
  //numChannels: 1,                 // 声道，支持 1 或 2， 默认是1
  // compiling: false,(0.x版本中生效,1.x增加中)  // 是否边录边转换，默认是false
})

// 绑定事件-打印的是当前录音数据
recorder.onprogress = function(params) {
  console.log('--------------START---------------')
  console.log('录音时长(秒)', params.duration);
  console.log('录音大小(字节)', params.fileSize);
  console.log('录音音量百分比(%)', params.vol);
  console.log('当前录音的总数据([DataView, DataView...])', params.data);

  console.log('--------------END---------------')
}

export default {
  name: "myRead",
  data() {
    return {
      tagName: '',
      number: undefined,
      input: '',
      fileList: [],// {name: url:}格式
      mp3Blob: undefined,
      form: {
        topic: '',
        region: '',
        picture: '',
        readUrl: '',
        tagNames: [],
        content: '',
        isPublic: 0
      }
    }
  },
  // 这里说明一下, this.$matomo是注册过后,自动会有得, 不需要进行其他得操作.
  created(){

    window._paq.push(['setCustomUrl', '/' + window.location.hash.substr(1)]);
    window._paq.push(['setDocumentTitle', '我的朗读']);
    window._paq.push(['trackPageView', '我的朗读']);
  },
  methods: {
    recordStart() {
      recorder.start().then(() => {
        // 开始录音
      }, (error) => {
        // 出错了
        console.log(`${error.name} : ${error.message}`);
      });
    },
    pause() {
      recorder.pause();
      this.number = recorder.duration
    },
    stop() {
      recorder.stop();
      this.number = recorder.duration
      this.mp3Blob = this.convertToMp3(recorder.getWAV());
    },
    play() {
      recorder.play();
    },
    resume() {
      recorder.resume()
    },
    getMp3Data(){
      recorder.download(this.mp3Blob, 'recorder', 'mp3');
    },
    convertToMp3(wavDataView) {
      // 获取wav头信息
      const wav = lamejs.WavHeader.readHeader(wavDataView); // 此处其实可以不用去读wav头信息，毕竟有对应的config配置
      const { channels, sampleRate } = wav;
      const mp3enc = new lamejs.Mp3Encoder(channels, sampleRate, 128);
      // 获取左右通道数据
      const result = recorder.getChannelData()
      const buffer = [];

      const leftData = result.left && new Int16Array(result.left.buffer, 0, result.left.byteLength / 2);
      const rightData = result.right && new Int16Array(result.right.buffer, 0, result.right.byteLength / 2);
      const remaining = leftData.length + (rightData ? rightData.length : 0);

      const maxSamples = 1152;
      for (let i = 0; i < remaining; i += maxSamples) {
        const left = leftData.subarray(i, i + maxSamples);
        let right = null;
        let mp3buf = null;

        if (channels === 2) {
          right = rightData.subarray(i, i + maxSamples);
          mp3buf = mp3enc.encodeBuffer(left, right);
        } else {
          mp3buf = mp3enc.encodeBuffer(left);
        }

        if (mp3buf.length > 0) {
          buffer.push(mp3buf);
        }
      }

      const enc = mp3enc.flush();

      if (enc.length > 0) {
        buffer.push(enc);
      }

      return new Blob(buffer, { type: 'audio/mp3' });
    },
    onSubmit() {
      var tagNameDTOs = []
      for (var i=0;i<this.form.tagNames.length;i++) {
        tagNameDTOs.push(this.form.tagNames[i].name)
      }
      var addRead = {
        topic : this.form.topic,
        content: this.form.content,
        picture: this.form.picture,
        isPublic: this.form.isPublic,
        readUrl: this.form.readUrl,
        tagNames: tagNameDTOs
      }
      console.log(addRead)
      var flag = addRead.topic != '' && addRead.content != '' && addRead.picture != ''
      && addRead.isPublic != '' && addRead.readUrl != '' && addRead.tagNames.length != 0;
      if (flag) {
        addMyRead(addRead).then(res => {
          if (res.body.data) {
            this.$message.success("发布成功")
            this.back()
          }
          else
            this.$message.error("请重新发布")
        })
      } else {
        this.$message.error("全部都需要填哦")
      }

    },
    handleAvatarSuccess(res, file) {
      this.form.picture = res.body.data
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isLt2M;
    },
    beforeAvatarUploadVideo(file) {
      const isAudio = file.type === 'audio/mpeg';
      const isVideo = file.type === 'video/mp4';

      if (!(isVideo || isAudio)) {
        this.$message.error('上传音频只能是 mp3/mp4 格式!');
      }
      return isVideo || isAudio;
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    addTag() {
      var flag = true;
      for (var i=0;i<this.form.tagNames.length;i++) {
        if (this.tagName == this.form.tagNames[i].name) {
          flag = false;
        }
      }
      if (flag) {
        var tag = {type : '', name : this.tagName}
        this.form.tagNames.push(tag)
      }
    },
    closeTag(tag) {
      this.form.tagNames.splice( this.form.tagNames.indexOf(tag), 1);
    },
    back() {
      this.$router.push({path:'/person/myDesign'})
    },
    upVideo() {
      if (this.mp3Blob != undefined) {
        var data = new FormData();
        data.append("file",this.mp3Blob);
        axios.post(
          "http://47.110.93.58:8081/user/myDesign/add/myReadVideo",
          data,
          {headers: {'Content-Type': 'multipart/form-data'}}
        ).then((res) => {
          this.form.readUrl = res.data.body.data
        })
      }
    },
    // 上传成功时的钩子
    uploadSuccess(res,file,fileList){
      this.form.readUrl = res.body.data
    },
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
